#include"list.h"
#include"freq.h"
#include<stdio.h>
#include<stdlib.h>

ListNode * ListNode_create(TreeNode * tn){

    ListNode * ln = malloc(sizeof(ListNode));
    if(NULL == ln){

        printf("malloc(sizeof(ListNode)) failed.\n");
        return NULL;
    }
    ln->tnptr = tn;
    ln->next = NULL;
    return ln;
}
// -此函数有问题 
// ListNode * ListNode_insert(ListNode * head,ListNode * ln){

//     if(NULL == head){

//         return ln;
//     }
//     if(NULL == ln){

//         printf("ERROR! ln is NULL.\n");
//         return head;
//     }
//     if(ln->next != NULL){

//         printf("ERROR! ln->next is not NULL.\n");
//     }
//     const int freq1 = head->tnptr->freq;
//     const int freq2 = head->tnptr->freq;
//     if(freq1 > freq2){

//         ln->next = head;
//         return ln;
//     }
//     head->next = ListNode_insert(head->next,ln);
//     return head;
// }
// -无递归版本
ListNode * ListNode_insert(ListNode * head,ListNode * ln){

    if(NULL == head){

        return ln;
    }
    ListNode * ptr = head;
    ListNode * prev = NULL;
    while(ptr && ptr->tnptr->freq < ln->tnptr->freq){

        prev = ptr;
        ptr = ptr->next;
    }
    if(NULL == ptr){

        prev->next = ln;
        return head;
    }else if(ptr == head){

        ln->next = head;
        return ln;
    }else{

        prev->next = ln;
        ln->next = ptr;
    }
    return head;
}

ListNode * ListNode_build(CharFreq * frequencies){

    int index = 0;
    // -找到第一个频率不是0的
    while(index < NUMLETTER && frequencies[index].freq == 0){

        index++;
    }
    if(index == NUMLETTER){

        return NULL;
    }
    ListNode * head = NULL;
    while(index < NUMLETTER){

        TreeNode * tn = TreeNode_create(frequencies[index].value,frequencies[index].freq);
        ListNode * ln = ListNode_create(tn);

        head = ListNode_insert(head,ln);
        index++;
    }
    return head;
}

void List_print(ListNode * head){

    if(NULL == head){

        return;
    }
    Tree_print(head->tnptr,0);
    List_print(head->next);
}

void ListNode_print(ListNode * ptrNode){

    if(NULL == ptrNode){

        printf("list node is null.\n");
    }else{

        printf("value = %c,freq = %d.\n",ptrNode->tnptr->value,ptrNode->tnptr->freq);
    }
}
